﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;

namespace TinyOsMessageForwarder
{
    public partial class ConnectionSettingsUC : UserControl
    {
        private TinyOSMessageForwarder tinyosMessageForwarder;

        public TinyOSMessageForwarder TinyosMessageForwarder
        {
            get { return tinyosMessageForwarder; }
            set {
                if (tinyosMessageForwarder != null)
                    tinyosMessageForwarder.TOS2MessageArrived -= new TOS2MessageArrivedDelegate(tinyosMessageForwarder_TOS2MessageArrived);
                tinyosMessageForwarder = value;
                if (tinyosMessageForwarder != null)
                    tinyosMessageForwarder.TOS2MessageArrived += new TOS2MessageArrivedDelegate(tinyosMessageForwarder_TOS2MessageArrived);
            }
        }

        public ConnectionSettingsUC()
        {
            InitializeComponent();
        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            if (tinyosMessageForwarder != null)
            {
                tinyosMessageForwarder.ConnectionString = tbConnection.Text;
                tinyosMessageForwarder.ConnectToTinyOS2();
            }
        }

        void tinyosMessageForwarder_TOS2MessageArrived(TinyOS2Message msg)
        {
            StringBuilder sb = new StringBuilder();

            DebugMessage dm = new DebugMessage(msg);
            if (dm != null)
            {
                sb.Append(dm.ToString());
            }
            else
            {
                sb.AppendLine("msg received, length=" + msg.Length);
                sb.AppendLine(msg.ToRawString());
            }
            tbLog.Invoke(new MethodInvoker(delegate
            {
                appender(sb.ToString());
            }));
        }

        private void appender(string s)
        {
            tbLog.AppendText(s);
        }

        private void btnDisconnect_Click(object sender, EventArgs e)
        {
            if (tinyosMessageForwarder != null)
                tinyosMessageForwarder.Disconnect();

        }
    }
}
